<template>
  <div class="login">
    <van-nav-bar
      title="酷安网"
      left-arrow
      @click-left="onClickLeft"
    > </van-nav-bar>
    <!-- 头像 -->
    <div class="touxiang">
      <van-image
        round
        width="2.5rem"
        height="2.5rem"
        src="https://img1.baidu.com/it/u=1703711924,229959213&fm=253&fmt=auto&app=120&f=PNG?w=192&h=192"
      />
    </div>
    <!-- 登录框 -->
    <div>
      <van-form @submit="Login">
        <van-cell-group class="inp">
          <van-field
            v-model="username"
            id="username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            left-icon="user-o"
            :rules="[
              { required: true, message: '用户名不能为空' },
              {
                validator,
                message: '请输入正确的手机号'
              }
            ]"
          />
          <van-field
            v-model="pwd"
            id="pwd"
            label="密码"
            type="password"
            placeholder="请输入密码"
            left-icon="closed-eye"
            name="pwd"
            :rules="[
              {
                required: true,
                message: '请填写密码'
              }
            ]"
          />
        </van-cell-group>
        <div
          class="btn_box"
          native-type="submit"
        >
          <van-button
            type="info"
            block
          >登录</van-button>
        </div>
        <div class="btn_box">
          <van-button
            type="default"
            block
            to="/register"
          >注册</van-button>
        </div>
        <div class="forget">
          <router-link to="/login">忘记密码</router-link>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      username: "",
      pwd: "",
    };
  },
  methods: {
    onClickLeft() {
      window.history.go(-1);
    },
    validator(val) {
      return /^1(3|4|5|6|7|8|9)\d{9}$/.test(val);
    },
    Login() {
      this.axios
        .post("apis/kuan_api/login.php", {
          username: this.username,
          pwd: this.pwd,
        })
        .then((res) => {
          console.log(res.data.error);
          if (res.data.error == false) {
            this.$store.state.users = res.data.users[0];
            sessionStorage.setItem("user", JSON.stringify(res.data.users[0]));
            this.$toast.success("登录成功");
            this.$router.push("/user");
          } else {
            this.$toast.fail("账号密码错误");
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
  },
};
</script>

<style scoped>
.touxiang {
  padding: 85px 0px;
  text-align: center;
}
.btn_box {
  margin-top: 15px;
  padding: 0px 15px;
}
.forget {
  padding-top: 20px;
  padding-left: 25px;
}
a {
  color: blue;
  font-size: 15px;
}
</style>
